/**
 * WebSocketPlugin will allow us to get new data from the server
 * without having to poll for changes on the frontend.
 *
 * This plugin is subscribed to host state property and logging
 * changes, indicated in the app header Health and Power status.
 *
 * https://github.com/openbmc/docs/blob/b41aff0fabe137cdb0cfff584b5fe4a41c0c8e77/rest-api.md#event-subscription-protocol
 */
import { useAuthenticationStore } from '@/store/Authentication/Authentication';
import { useGlobalStore } from '@/store/global';
import { useEventLogStore } from '@/store/Diagnostic/EventLog/EventLogStore';
import { usePowerControlStore } from '../SystemManagement/Power/PowerControlStore';
import wsUrl from '@/utilities/wsUrlTool';

export let ws: WebSocket;

const data = {
  paths: [
    '/xyz/openbmc_project/state/host0',
    '/xyz/openbmc_project/logging',
    '/xyz/openbmc_project/sensors/power/total_power',
  ],
  interfaces: [
    'xyz.openbmc_project.State.Host',
    'xyz.openbmc_project.Logging.Entry',
    'xyz.openbmc_project.Sensor.Value',
  ],
};

export const initWebSocket = () => {
  const socketDisabled =
    import.meta.env.VUE_APP_SUBSCRIBE_SOCKET_DISABLED === 'true' ? true : false;
  if (socketDisabled) return;
  const token = useAuthenticationStore().token;
  const wsURL = wsUrl(`wss://${location.host}/subscribe`);

  ws = new WebSocket(wsURL, [token as string]);
  ws.onopen = async () => {
    ws.send(JSON.stringify(data));
    // Get time when it start to calculate power.
    await usePowerControlStore().getPowerChassisId();
    usePowerControlStore().startCalculate();
    usePowerControlStore()
      .getPowerControl()
      .then(() => {
        usePowerControlStore().setpowerChartData1();
      });
  };
  ws.onerror = (event) => {
    console.error(event);
    clearInterval(usePowerControlStore().powerChartData1Interval);
  };
  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    const eventInterface = data.interface;
    const path = data.path;

    if (eventInterface === 'xyz.openbmc_project.State.Host') {
      const {
        properties: { CurrentHostState } = {} as { CurrentHostState: any },
      } = data;
      if (CurrentHostState) {
        useGlobalStore().setServerStatus(CurrentHostState);
      }
    } else if (path === '/xyz/openbmc_project/logging') {
      useEventLogStore().getEventLogData();
    }
    if (
      eventInterface === 'xyz.openbmc_project.Sensor.Value' &&
      path === '/xyz/openbmc_project/sensors/power/total_power'
    ) {
      const powerConsumption = data.properties.Value;
      usePowerControlStore().setPowerConsumptionValue(powerConsumption);
    }
  };
  ws.close = () => {
    clearInterval(usePowerControlStore().powerChartData1Interval);
  };
};

if (useAuthenticationStore().isLoggedIn) initWebSocket();
